<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <div class="login-content">
      <div class="login-form-wrapper">
        <a-form 
          v-if="activeTab === 'password'"
          ref="passwordForm" 
          :model="passwordForm" 
          :rules="passwordRules" 
          class="login-form"
        >
          <a-form-item name="email">
            <a-input 
              v-model:value="passwordForm.email" 
              placeholder="邮箱"
              class="form-input"
            ></a-input>
          </a-form-item>

          <a-form-item name="password">
            <a-input-password 
              v-model:value="passwordForm.password" 
              placeholder="密码"
              class="form-input"
            ></a-input-password>
          </a-form-item>

          <div class="action-buttons">
            <a-button 
              v-if="activeTab === 'password'"
              @click="activeTab = 'code'"
              class="switch-btn"
            >
              验证码登录
            </a-button>
            <a-button 
              v-else
              @click="activeTab = 'password'"
              class="switch-btn"
            >
              密码登录
            </a-button>
            <a-button 
              @click="$router.push('/register')"
              class="register-btn"
            >
              注册
            </a-button>
          </div>

          <a-form-item>
            <a-button 
              type="primary" 
              @click="handlePasswordLogin"
              :loading="loginLoading"
              class="submit-btn"
            >
              登录
            </a-button>
          </a-form-item>
        </a-form>

        <a-form 
          v-else
          ref="codeForm" 
          :model="codeForm" 
          :rules="codeRules" 
          class="login-form"
        >
          <a-form-item name="email">
            <a-input 
              v-model:value="codeForm.email" 
              placeholder="邮箱"
              class="form-input"
              @blur="handleEmailBlur"
            ></a-input>
          </a-form-item>

          <a-form-item name="code">
            <div class="code-input-group">
              <a-input 
                v-model:value="codeForm.code" 
                placeholder="验证码"
                class="form-input code-input"
              ></a-input>
              <a-button 
                :disabled="!canSendCode || countdown > 0"
                @click="sendVerificationCode"
                class="get-code-btn"
              >
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </a-button>
            </div>
          </a-form-item>

          <div class="action-buttons">
            <a-button 
              v-if="activeTab === 'password'"
              @click="activeTab = 'code'"
              class="switch-btn"
            >
              验证码登录
            </a-button>
            <a-button 
              v-else
              @click="activeTab = 'password'"
              class="switch-btn"
            >
              密码登录
            </a-button>
            <a-button 
              @click="$router.push('/register')"
              class="register-btn"
            >
              注册
            </a-button>
          </div>

          <a-form-item>
            <a-button 
              type="primary" 
              @click="handleCodeLogin"
              :loading="loginLoading"
              :disabled="!codeForm.code"
              class="submit-btn"
            >
              登录
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
import { useUserStore } from '@/stores/user';

export default {
  name: 'LoginView',
  mounted() {
    if (this.$route.query.expired) {
      this.$message.warning('身份信息已过期，请重新登录');
    }
  },
  data() {
    // 邮箱验证规则
    const validateEmail = async (rule, value) => {
      if (!value) {
        throw new Error('请输入邮箱');
      }
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(value)) {
        throw new Error('请输入有效的邮箱地址');
      }
    };

    return {
      activeTab: 'password',
      passwordForm: {
        email: '',
        password: ''
      },
      passwordRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      codeForm: {
        email: '',
        code: ''
      },
      codeRules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码为6位数字', trigger: 'blur' }
        ]
      },
      countdown: 0,
      canSendCode: false,
      loginLoading: false
    };
  },
  methods: {
    handleEmailBlur() {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      this.canSendCode = emailRegex.test(this.codeForm.email);
    },
    async sendVerificationCode() {
      try {
        const userStore = useUserStore();
        const success = await userStore.sendVerificationCode(this.codeForm.email);
        if (success) {
          this.$message.success('验证码发送成功');
          this.startCountdown();
        } else {
          this.$message.error('验证码发送失败');
        }
      } catch (error) {
        this.$message.error(error || '验证码发送失败');
      }
    },
    startCountdown() {
      this.countdown = 30;
      const timer = setInterval(() => {
        this.countdown--;
        if (this.countdown <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    },
    async handlePasswordLogin() {
      try {
        await this.$refs.passwordForm.validate();
        this.loginLoading = true;
        const { email, password } = this.passwordForm;
        const userStore = useUserStore();
        console.log("vue: call login function");
        const result = await userStore.login({ email, password });
        if (result.success) {
          this.$message.success('登录成功');
          // 确保用户信息加载完成后再跳转
          await this.$nextTick();
          const redirect = this.$route.query?.redirect || '/';
          this.$router.push(redirect);
        } else {
          this.$message.error(result.message || '登录失败');
        }
        this.loginLoading = false;
      } catch (error) {
        this.$message.error(error.message || '登录失败');
        this.loginLoading = false;
      }
    },
    async handleCodeLogin() {
      try {
        await this.$refs.codeForm.validate();
        this.loginLoading = true;
        const { email, code} = this.codeForm;
        const userStore = useUserStore();
        const result = await userStore.codeLogin(email, code);
        if (result.success) {
          this.$message.success('登录成功');
          // 确保用户信息加载完成后再跳转
          await this.$nextTick();
          const redirect = this.$route.query?.redirect || '/';
          this.$router.push(redirect);
        } else {
          this.$message.error(result.message || '登录失败');
        }
        this.loginLoading = false;
      } catch (error) {
        this.$message.error(error.message || '登录失败');
        this.loginLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  width: 50%;
  margin: 30px auto;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  min-height: 400px;
}

.login-container h2 {
  margin: 20px 0;
  font-size: 24px;
  text-align: center;
}

.login-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  padding: 20px 0 100px;
  width: 70%;
  margin: 0 auto;
}

.login-form-container {
  margin: 0 auto;
}

.login-form-wrapper {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-input {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin: 20px 0;
}

.action-buttons .ant-btn {
  flex: 1;
  height: 40px;
}

.submit-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.code-input-group {
  display: flex;
}

.code-input {
  flex: 1;
  height: 40px;
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
  border-right: none;
}

.get-code-btn {
  width: 120px;
  height: 40px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border: 1px solid #d9d9d9;
  border-left: none;
  margin-left: -1px;
}
</style>
